package com.gzyj.video.handler.rtp;


import com.gzyj.video.common.Packet;
import com.gzyj.video.decode.Jtt1078Decoder;
import com.gzyj.video.utils.StackUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by matrixy on 2019/4/9.
 */
public class Jtt1078MessageDecoder extends ByteToMessageDecoder {
    static Logger logger = LoggerFactory.getLogger(Jtt1078MessageDecoder.class);

    byte[] block = new byte[4096];

    private String version="1078";

    Jtt1078Decoder decoder = new Jtt1078Decoder(version);

    public Jtt1078MessageDecoder(String version) {
        if(StringUtils.isNotEmpty(version)){
            this.version=version;
            this.decoder=new Jtt1078Decoder(this.version);
        }

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        try {
            int length = in.readableBytes();
            for (int i = 0, k = (int) Math.ceil(length / 512f); i < k; i++) {
                int l = i < k - 1 ? 512 : length - (i * 512);
                in.readBytes(block, 0, l);

                decoder.write(block, 0, l);

                while (true) {
                    Packet p = decoder.decode();
                    if (p == null) break;

                    out.add(p);
                }
            }
        }catch (Exception e){
            logger.error("读取数据报错 \n {}", StackUtils.getStackInfo(e));
        }



    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ctx.close();
        if(!ctx.channel().isActive()){
            logger.error("连接已关闭 读取字节异常信息 \n {}", StackUtils.getStackInfo(cause));
            ctx.close();
        }else{
            ctx.fireExceptionCaught(cause);
            logger.error("################## \n {}", StackUtils.getStackInfo(cause));
        }

    }
}
